import React, { Component } from 'react';
import BaseComponent from '@/components/BaseComponent';
import styles from './index.less';
import { Button, Card, Input, Form, Row, Col } from 'antd';
import { connect } from 'dva';

/**
 * 修改密码
 */
@connect(({ user, tkmsysuser, loading }) => ({
  currentUser: user.currentUser,
  isUpdating: loading.effects['tkmsysuser/updateUserPassword'],
}))
@Form.create()
class SettingPassword extends BaseComponent {
  constructor(props) {
    super(props);
    this.state = {
      confirmDirty: false,
    };
  }

  /**
   * 提交按钮
   * */
  handleSubmit = e=> {
    const { form } = this.props;
    form.validateFieldsAndScroll((err, values) => {
      if (err !== null) {
        e.preventDefault();
      } else {
        //二次确认密码
        let secondVal = form.getFieldValue('confirmPassword');
        if (this.props.isUpdating) {
          return;
        }
        const hide = this.loadingMessage('操作中,请稍后...');
        this.execHttp('tkmsysuser/updateUserPassword', {
          id: this.props.currentUser.id,
          password: secondVal,
        })
          .then(resp => {
            hide();
            const { success } = resp;
            if (success) {
              //修改成功，操作登陆状态
              this.successMessage('修改成功！');
            } else {
              this.errorMessage('修改失败！');
            }
          })
          .catch(err => {
            this.errorMessage('提交失败！');
          });
      }
    });
  };

  /**
   * 重置按钮
   * */
  handleReset = () => {
    const { form } = this.props;
    form.resetFields();
  };

  /**
   * 第一次密码校验
   * */
  validateToNextPassword = (rule, value, callback) => {
    const { form } = this.props;
    if (value && this.state.confirmDirty) {
      form.validateFields(['confirmPassword'], { force: true });
    }
    callback();
  };

  /**
   * 第二次密码校验
   * */
  compareToFirstPassword = (rule, value, callback) => {
    const { form } = this.props;
    if (value && value !== form.getFieldValue('password')) {
      callback('两次密码输入的不一致！');
    } else {
      callback();
    }
  };

  /**
   * 失去焦点校验规则
   * */
  handleConfirmBlur = e => {
    const { value } = e.target;
    this.setState({ confirmDirty: this.state.confirmDirty || !!value });
  };

  render() {
    const { form } = this.props;
    const { getFieldDecorator } = form;
    return (
      <div className={styles.settingPassword}>
        <Form className="ant-advanced-search-form" onSubmit={this.handleSubmit}>
          <Card>
            <Row gutter={30}>
              <Form.Item
                hasFeedback
                label={'密码'}
                colon={true}
                labelCol={{ span: 8 }}
                wrapperCol={{ span: 16 }}
              >
                {getFieldDecorator('password', {
                  rules: [
                    {
                      required: true,
                      message: '不可为空！',
                    },
                    {
                      message: '密码必须包含数字加英文字母加特殊字符并且长度在8-16之间！',
                      pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_])[a-zA-Z\d\W_]{8,}$/g,
                      // pattern: /^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[!@#$\%\^\&\*\(\)])[0-9a-zA-Z!@#$\%\^\&\*\(\)]{8,16}/g,
                    },
                    {
                      validator: this.validateToNextPassword,
                    },
                  ],
                })(<Input.Password style={{ width: 300 }} />)}
              </Form.Item>
              <Form.Item
                hasFeedback
                label={'确认密码'}
                colon={true}
                labelCol={{ span: 8 }}
                wrapperCol={{ span: 16 }}
              >
                {getFieldDecorator('confirmPassword', {
                  rules: [
                    {
                      required: true,
                      message: '不可为空！',
                    },
                    {
                      message: '密码必须包含数字加英文字母加特殊字符并且长度在8-16之间！',
                      pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_])[a-zA-Z\d\W_]{8,}$/g,
                      // pattern: /^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[!@#$\%\^\&\*\(\)])[0-9a-zA-Z!@#$\%\^\&\*\(\)]{8,16}/g,
                    },
                    {
                      validator: this.compareToFirstPassword,
                    },
                  ],
                })(<Input.Password style={{ width: 300 }} onBlur={this.handleConfirmBlur} />)}
              </Form.Item>
            </Row>
            <Row gutter={30}>
              <Col span={30} style={{ textAlign: 'center' }}>
                <Button type="primary" htmlType="submit">
                  确认
                </Button>
                <Button
                  style={{
                    marginLeft: 20,
                  }}
                  onClick={this.handleReset}
                >
                  重置
                </Button>
              </Col>
            </Row>
          </Card>
        </Form>
      </div>
    );
  }
}

export default SettingPassword;
